<?php
/**
 * This is Areas controller file. 
 *
 * @copyright     Copyright 2008-2010, LilCake.net
 * @link          http://lilcake.net LilCake.net
 * @package       lil
 * @subpackage    lil.controllers
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
/**
 * AreasController class
 *
 * @uses          LilAppController
 * @package       lil
 * @subpackage    lil.controllers
 */
class AreasController extends LilAppController {
/**
 * name property
 *
 * @var string 'Areas'
 * @access public
 */
	var $name = 'Areas';
/**
 * uses property
 *
 * @var array
 * @access public
 */
	var $uses = array('Lil.Area', 'Lil.AreasUser', 'Lil.User');
/**
 * beforeFilter method
 *
 * @access public
 * @return void
 */
	function beforeFilter() {
		if (!empty($this->Auth)) {
			$this->Auth->allow('index', 'view');
		}
		parent::beforeFilter();
	}
/**
 * isAuthorized method
 *
 * @access public
 * @return bool
 */
	function isAuthorized() {
		if (!parent::isAuthorized()) return false;
		if (in_array($this->params['action'], array('index', 'view'))) return true;
		
		if (isset($this->Auth) && !Configure::read('Lil.allowUsersAnything')) {
			if (in_array($this->params['action'], array('admin_edit', 'admin_delete', 'admin_select'))) {
				if (!empty($this->params['pass'][0])) {
					$assoc = Configure::read('Lil.userAssociation');
					
					// action by slug
					if (is_numeric($this->params['pass'][0]) || Validation::uuid($this->params['pass'][0])) {
						$area_id = $this->params['pass'][0];
					} else {
						$area_id = $this->Area->field('id', array(
							'Area.'.Configure::read('Lil.areaSlugField') => $this->params['pass'][0]
						));
					}
					
					return $this->User->canAccessArea($this->Auth->user('id'), $area_id);
					
				} else if ($this->params['action'] != 'admin_select') {
					// user can select no area (return to admin mode without preselected area)
					return false;
				}
			} else if ($this->params['action'] == 'admin_add') {
				return $this->Auth->user(Configure::read('Lil.userAdminField'));
			} else if ($this->params['action'] == 'admin_list') {
				return true;
			}
		}
		return true;
	}
/**
 * index method
 *
 * @access public
 * @return bool
 */
	function index() {
		if (!$areas = Configure::read('Lil.noAreas')) {
			$areas = $this->Area->find('all', array('recursive' => 0));
		}
		if (sizeof($areas) == 1) {
			$this->redirect(array(
				'plugin'     => 'lil',
				'controller' => 'areas',
				'action'     => 'index',
				'area'       => $areas[0]['Area'][Configure::read('Lil.areaSlugField')]
			));
		} else {
			$this->set('areas', $areas);
		}
	}
/**
 * view method
 *
 * @param string slug  
 * @access public
 * @return void
 */
	function view($slug) {
		$this->redirect('/' . $this->params['plugin'] . '/' . $slug);
	}
/**
 * admin_dashboard method
 *
 * @access public
 * @return void
 */
	function admin_dashboard() {
		$lang = null;
		if (isset($this->params['lang'])) $lang = $this->params['lang'];
		elseif (isset($this->params['named']['lang'])) $lang = $this->params['named']['lang'];
		
		if (!empty($lang) && in_array($lang, Configure::read('Lil.languages'))) {
			$this->Cookie->write('Lil.lang', $lang, false, '1 year');
			Configure::write('Config.language', $lang);
		}
	}
/**
 * admin_index method
 *
 * @access public
 * @return void
 */
	function admin_index() {
		$this->Area->recursive = 0;
		$params = array();
		
		if (isset($this->Auth) && (
			!$this->Auth->user(Configure::read('Lil.userAdminField')) && 
			!Configure::read('Lil.allowUsersAnything')))
		{
			$assoc = Configure::read('Lil.userAssociation');
			
			$params = array(
				'conditions' => array(
					'id' => $this->AreasUser->find('list', array(
						'conditions' => array($assoc['foreignKey'] => $this->Auth->user('id')), 
						'fields'     => array('id', $assoc['associationForeignKey'])
					))
				)
			); 
		}
		
		$this->set('paginate', false);
		if (!$data = Configure::read('Lil.noAreas')) {
			$params = $this->callPluginHandlers('before_area_admin_index_params', array('params' => $params));
			$this->paginate = $params['params'];
			
			$data = $this->paginate('Area');
			$this->set('paginate', true);
		}
		
		$this->set(compact('data'));
	}
/**
 * admin_list method
 *
 * @access public
 * @return void
 */
	function admin_list() {
		$this->Area->recursive = 0;
		$params = array();
		
		if (isset($this->Auth) && (
			!$this->Auth->user(Configure::read('Lil.userAdminField')) &&
			!Configure::read('Lil.allowUsersAnything')))
		{
			$assoc = Configure::read('Lil.userAssociation');
			$params = array(
				'conditions' => array(
					'id' => $this->AreasUser->find('list', array(
						'conditions' => array($assoc['foreignKey'] => $this->Auth->user('id')),
						'fields'     => array('id', $assoc['associationForeignKey'])
					))
				)
			);
		}
		
		if (!$areas = Configure::read('Lil.noAreas')) {
			$params = $this->callPluginHandlers('before_area_admin_list_params', array('params' => $params));
			$this->paginate = $params['params'];
			
			$areas = $this->paginate('Area');
		}
		
		if (sizeof($areas) == 1) {
			$this->redirect(array(
				'admin'  => true,
				'action' => 'select',
				$areas[0]['Area'][Configure::read('Lil.areaSlugField')],
			));
		}
		
		$this->set('data', $areas);
	}
/**
 * admin_select method
 *
 * This method select area on which all operations will be performed.
 *
 * @param int $id  
 * @access public
 * @return void
 */
	function admin_select($id = null) {
		if (((is_numeric($id) || Validation::uuid($id)) && $this->setAdminAreaId($id)) ||
			(is_string($id) && $this->setAdminAreaSlug($id)))
		{
			$this->Session->setFlash(__d('lil', 'Area has been selected.', true));
			$this->redirect(array('controller' => 'areas', 'action' => 'dashboard', 'admin' => true));
		} else if (is_null($id)) {
			$this->clearAdminArea();
			$this->Session->setFlash(__d('lil', 'Area has been cleared.', true));
			$this->redirect(array('controller' => 'areas', 'action' => 'dashboard', 'admin' => true));
		} else {
			$this->error404();
		}
	}
/**
 * admin_add method
 *
 * @access public
 * @return void
 */
	function admin_add() {
		if(!empty($this->data)) {
			if($this->Area->saveAll($this->data)) {
				$this->Session->setFlash(__d('lil', 'A new area has been created.', true));
				$this->redirect(array(
					'admin'      => true,
					'plugin'     => 'lil',
					'controller' => 'areas',
					'action'     => 'index'
				));
			} else {
				$this->Session->setFlash(__d('lil', 'Please verify that the information is correct.', true), 'error');
			}
		}
		
		$User = ClassRegistry::init('Lil.User');
		$this->set('users', $User->find('list', array('conditions' => array('User.admin' => false))));
	}
/**
 * admin_edit method
 *
 * @param int $id  
 * @access public
 * @return void
 */
	function admin_edit($id = null) {
		if(!empty($this->data)) {
			if($this->Area->saveAll($this->data)) {
				$this->Session->setFlash(__d('lil', 'Area has been saved.', true));
				$this->redirect(array(
					'admin'      => true,
					'plugin'     => 'lil',
					'controller' => 'areas',
					'action'     => 'index'
				));
			} else {
				$this->Session->setFlash(__d('lil', 'Please verify that the information is correct.', true), 'error');
			}
		} else if (empty($id) || !($this->data = $this->Area->find(
			'first', 
			array(
				'conditions' => array('Area.id' => $id),
				'contain'    => 'User'
			)
		))) {
			$this->error404();
		}
		
		$User = ClassRegistry::init('Lil.User');
		$this->set('users', $User->find('list', array('conditions' => array('User.admin' => false))));
	}
/**
 * admin_delete method
 *
 * @param int $id  
 * @access public
 * @return void
 */
	function admin_delete($id=null) {
		$this->Area->recursive = -1;
		if (!empty($id) && $data = $this->Area->findById($id)) {
			$this->Area->delete($id);
			$this->Session->setFlash(__d('lil', 'Area has been deleted.', true));
			
			if ($id == $this->getAdminAreaId()) {
				// redirect to area selection after deleting current area
				$this->redirect(array('admin' => true, 'action' => 'list'));
			} else {
				$this->redirect(array('admin' => true, 'action' => 'index'));
			}
		} else {
			$this->error404();
		}
	}

}
?>